﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using API1;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace ApiConsulTest.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class TestController : ControllerBase
    {
        private string _serviceAddress=null;      
      

        private readonly ILogger<TestController> _logger;

        public IOptions<ServiceDisvoveryOptions> _Options { get; }
        public HttpClient _httpClient { get; }

        public TestController(ILogger<TestController> logger,
            Consul.ConsulClient consulClient,
            IOptions<ServiceDisvoveryOptions> options,
            HttpClient httpClient
            )
        {
            _logger = logger;
            _Options = options;
            _httpClient = httpClient;
            var services = consulClient.Agent.Services().Result.Response;
            var temp = services.Values.FirstOrDefault(n => n.Service == options.Value.ServiceName);
            if(temp!=null)
            {
                _serviceAddress = $"http://{temp.Address}:{temp.Port}";
            }
        }

        [HttpGet]
        public async Task<string> Get()
        {
            string result = "error";
            if (!string.IsNullOrEmpty(_serviceAddress))
            {
                var response = await _httpClient.GetAsync($"{_serviceAddress}/api/values");
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    result = await response.Content.ReadAsStringAsync();
                }
            }
            return result;
        }
    }
}
